﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using ZX.BLL.ClientMobi.Message;
using ZX.EHR.Library;
using System.Collections;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Data;

using ZX.SYS.Library.AdiDl.PageBusiness;
using System.Text.RegularExpressions;

namespace ZX.WebApp.Extend
{
   public partial class MsgreplyModify : System.Web.UI.Page
    {




        private DatUser user = new DatUser();

        private DatSysNewsMonthInfo news = null;

        private DatSysNewsMonthInfoInfo newsInfo = null;

        private IDictionary<int, object> newsInfoDic = new Dictionary<int, object>();

        public int CheckedState = 0;

        public string PageStatestring;

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {

                this.caonima.Visible = false;
                 PageStatestring = (Request["PageState"] == null) ? "Modify" : Request["PageState"].ToString();
                //页面状态 
                new PageState().GetInstance(this.Page, PageStatestring).ShowContainer();

                this.txtID.Value="";
                Button1.Text = "提交";
                if (Request["id"] != null && Request["id"].ToString().Trim() != "")
                {
                    this.txtID.Value = Request["id"].ToString().Trim();
                    Button1.Text = "修改";
                }
                else
                {
                    //新建回复（给标题固定）
                    //this.title.Text=
                    CheckSession();
                    this.title.Text = this.ltTitle.Text = user.UName + "-----" + DateTime.Now.ToString("yyyy年MM月");
                    this.ltCreatePeopleName.Text = this.CreatePeopleName.Text = user.UName;
                }
                
                InitData();

            }
            else
            {
                SetNewsData();
            }


        }

        //内容历史记录
        private void ListNewsData()
        {
            IDictionary<string, object> sqlParams = new Dictionary<string, object>();
            sqlParams.Add("t-sql", " select * From DatSysNewsMonth_log where MessageID='" + this.txtID.Value.Trim() + "' order by opttime desc");
            System.Data.DataTable ddlog = new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable;

            IDictionary<string, object> sqlParamss = new Dictionary<string, object>();
            sqlParamss.Add("t-sql", "select * From V_MsgReplyOne where ID='" + this.txtID.Value.Trim() + "'");
            DataTable dt = new RoleBase().Instance().GetListByTSQL(sqlParamss) as System.Data.DataTable;

            string cc = dt.Rows[0]["content"].ToString();
            
            if (ddlog != null && ddlog.Rows.Count > 0)
            {
                cc = ddlog.Rows[0]["AfterVal"].ToString();
                this.DropDownList1.Items.Clear();
                this.DropDownList1.Items.Add(new ListItem("请选择历史版本", ""));
                this.DropDownList1.DataSource = ddlog;
                this.DropDownList1.DataTextField = "OptTime";
                this.DropDownList1.DataValueField = "ID";
                this.DropDownList1.DataBind();
            }
            this.tbEditContent.Text = Regex.Replace(cc, "(\r\n){2}", "\r\n");
            this.Literal3.Text = Regex.Replace(cc, "\r\n", "<br/>");
        }

        private void SetNewsData()
        {
            if (!string.IsNullOrEmpty(this.txtID.Value.Trim().ToString()))
            {
                IDictionary<string, object> sqlParams = new Dictionary<string, object>();
                sqlParams.Add("t-sql", "select top 1 * From DatSysNewsMonth where ID='" + this.txtID.Value.Trim().ToString() + "' ");
                news = DatSysNewsMonthInfo.PopulateFromDataRow((new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable).Rows[0]);
            }

        }

        private void InitData()
        {
           
            #region 绑定数据

            System.Data.DataTable checkBoxListSource = null;

            IDictionary<string, object> cbsql = new Dictionary<string, object>();
            cbsql.Add("t-sql", "select DeptID, DeptName From [DatDepartment] as x where deptType=3  and (x.ExpireDate >= GETDATE() or x.ExpireDate = '1900-01-01' or x.ExpireDate is null) order by len(DeptName) desc");
            checkBoxListSource = new RoleBase().Instance().GetListByTSQL(cbsql) as System.Data.DataTable;
            if (checkBoxListSource != null && checkBoxListSource.Rows.Count > 0)
            {
                Repeater1.DataSource = checkBoxListSource;
                Repeater1.DataBind();
            }
            #endregion

            #region 初始化赋值
            SetNewsData();
            if (news != null)
            {
                IDictionary<string, object> sqlParams = new Dictionary<string, object>();
                sqlParams.Add("t-sql", "select top 1 recevePeopleID From DatSysNewsMonthInfo where NID='" + news.ID + "'");
                DataRow drTemp = (new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable).Rows[0];


                sqlParams = null;

                this.ltCreatePeopleName.Text = this.CreatePeopleName.Text = news.CreatePeopleName.ToString();

                this.ltHide_ID.Text = news.ID.ToString();
                this.ltHide_AddUser.Text = drTemp["recevePeopleID"].ToString();


                this.title.Text = this.ltTitle.Text = news.Title;
                this.content.Text = this.ltContent.Text = news.Content;


                //---------------------------------------
                this.ltBM.Text = "";
                this.ltContent.Text = Regex.Replace(this.ltContent.Text, "(\r\n){2}", "\r\n");
                this.ltContent.Text = Regex.Replace(this.ltContent.Text, "\r\n", "<br/>");


                sqlParams = new Dictionary<string, object>();
                sqlParams.Add("t-sql", "select DeptID From DatSysNewsMonth_Depart where MessageID='" + news.ID + "'");

                DataTable tableDepart = new RoleBase().Instance().GetListByTSQL(sqlParams) as DataTable;
                if (tableDepart != null && tableDepart.Rows.Count > 0)
                {
                    for (int i = 0; i < this.Repeater1.Items.Count; i++)
                    {
                        Literal litTemp = this.Repeater1.Items[i].FindControl("Literal1") as Literal;
                        if (litTemp != null)
                        {
                            foreach (DataRow dr in tableDepart.Rows)
                            {
                                if (dr["DeptID"].ToString() == litTemp.Text.Trim())
                                {
                                    if (this.Repeater1.Items[i].FindControl("hide2") as Literal != null)
                                    {
                                        this.ltBM.Text += ((this.ltBM.Text != "") ? "," : "") + (this.Repeater1.Items[i].FindControl("hide2") as Literal).Text;
                                    }

                                    (this.Repeater1.Items[i].FindControl("cbRule") as CheckBox).Checked = true;
                                    break;
                                }

                            }

                        }

                    }
                }

            }
            #endregion


            
            if (this.txtID.Value.ToString().Trim()!="")
            {
                ListNewsData();
            }
        }

        private object GetDataItemsCheckedValue(bool isResetCheckedState)
        {
            string[] resultArr = null;
            string result = string.Empty;
            for (int i = 0; i < this.Repeater1.Items.Count; i++)
            {
                CheckBox cb = this.Repeater1.Items[i].FindControl("cbRule") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    if (isResetCheckedState)
                        cb.Checked = false;
                    else
                        result += ((result == string.Empty) ? "" : ",") + (this.Repeater1.Items[i].FindControl("Literal1") as Literal).Text;
                }
            }

            resultArr = (result != string.Empty) ? result.Split(',') : null;
            return resultArr;

        }

        private void CheckSession()
        {
            try
            {
                user = null;
                if (HttpContext.Current.Session["User"] != null)
                {
                    user = (DatUser)HttpContext.Current.Session["User"];
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "scirpt", "SessionTimeoutMSG()", true);
                }
            }
            catch (Exception)
            {

                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "scirpt", "SessionTimeoutMSG()", true);

            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string title = this.title.Text.Trim();
            string content = this.content.Text.Trim();
            CheckSession();

            #region 初始化参数
            if (news == null) news = new DatSysNewsMonthInfo();
            if (newsInfo == null) newsInfo = new DatSysNewsMonthInfoInfo();
            #endregion

            if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(content))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "scirpt", "myfunction();", true);
                return;
            }

            /*获取部门数据*/
            string[] ids = GetDataItemsCheckedValue(false) as string[];

            if (ids == null || ids.Length <= 0)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "scirpt", "DepartmemtMsg();", true);
                return;
            }


            RoleBase defaultRole = new RoleBase();
            defaultRole.Title = "默认规则组";

            IMessagePly MsgInstance = defaultRole.Instance();
            if (string.IsNullOrEmpty(this.txtID.Value.Trim().ToString()))
            {

                news.ID = Guid.NewGuid().ToString();

                news.AddUser = user.UserID.ToString();
                news.CreateDate = DateTime.Now;
                news.Title = title;
                news.Content = content;
                news.RecevePeopleName = "赵云娇";
                news.CreatePeopleName = user.UName;
                news.SendMode = "Post";
                news.ISDelete = false;
                news.Classify = 99;
            }
            else
            {
                news.Title = title;
                news.Content = content;
            }

            newsInfo.ID = Guid.NewGuid().ToString();
            newsInfo.NID = news.ID;
            newsInfo.RecevePeopleID = "";
            newsInfo.ReadDate = DateTime.Now;
            newsInfo.IsDelete = false;

            newsInfoDic.Add(1, newsInfo);

            if (this.txtID.Value.ToString().Trim()=="")
            {
                //try
                //{
                MsgInstance.Save(news, newsInfoDic);
                /*反馈部门提交*/
                string sqlParams = "";
                foreach (string arr in ids)
                {
                    sqlParams += " Insert into DatSysNewsMonth_Depart ([ID]  ,[MessageID]  ,[DeptID]  ,[OptTime]) values (NEWID(), '" + news.ID + "', '" + arr + "', GETDATE())";
                }

                IDictionary<string, object> sqlParamsContainer = new Dictionary<string, object>();
                sqlParamsContainer.Add("action", "ExecuteScalar");
                sqlParamsContainer.Add("t-sql", sqlParams);
                MsgInstance.GetListByTSQL(sqlParamsContainer);
                GetDataItemsCheckedValue(true);

                //}
                //catch (Exception)
                //{

                //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "scirpt", "OptMssage('Error');", true);
                //}
                ClearTextBoxVal();

            }
            else
            {
                StringBuilder sqlParams = new StringBuilder();
                sqlParams.Append("Update DatSysNewsMonth set ");
                sqlParams.AppendFormat("title='{0}', ", news.Title);
                sqlParams.AppendFormat("content='{0}' ", news.Content);
                sqlParams.AppendFormat("where ID='{0}'", this.txtID.Value.ToString().Trim());

                IDictionary<string, object> sqlParamsContainer = new Dictionary<string, object>();
                sqlParamsContainer.Add("action", "ExecuteScalar");
                sqlParamsContainer.Add("t-sql", sqlParams.ToString());
                MsgInstance.GetListByTSQL(sqlParamsContainer);

                /*反馈部门修改*/
                string strSqlParams = "";
                strSqlParams = "delete From DatSysNewsMonth_Depart where MessageID='" + this.txtID.Value.ToString().Trim() + "'";
                foreach (string arr in ids)
                {
                    strSqlParams += " Insert into DatSysNewsMonth_Depart ([ID]  ,[MessageID]  ,[DeptID]  ,[OptTime]) values (NEWID(), '" + this.txtID.Value.ToString().Trim() + "', '" + arr + "', GETDATE())";
                }

                sqlParamsContainer = null;
                sqlParamsContainer = new Dictionary<string, object>();
                sqlParamsContainer.Add("action", "ExecuteScalar");
                sqlParamsContainer.Add("t-sql", strSqlParams);
                MsgInstance.GetListByTSQL(sqlParamsContainer);
            }
            string smsg = this.txtID.Value.Trim() == "" ? "提交" : "修改";
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "scirpt", "success('" + smsg + "')", true);

        }

        private void ClearTextBoxVal()
        {
            this.title.Text = "";
            this.content.Text = "";
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            IDictionary<string, object> sqlParams = new Dictionary<string, object>();
            sqlParams.Add("t-sql", "select * From V_MsgReplyOne where ID='" + this.txtID.Value.Trim() + "'");
            DataTable dt = new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable;
            //((DataTable)MsgReplyPage.V_MsgReply).Rows[0]["content"]
            if ((sender as DropDownList) != null && string.IsNullOrEmpty((sender as DropDownList).SelectedValue))
            {
                string result1 = dt.Rows[0]["content"].ToString();
                result1 = Regex.Replace(result1, "(\r\n){2}", "\r\n");
                this.Literal3.Text = Regex.Replace(result1, "\r\n", "<br/>");
                this.caonima.Visible = false;
                return;
            }

            sqlParams.Clear();
            sqlParams.Add("t-sql", " select top 1 * From DatSysNewsMonth_log where ID='" + (sender as DropDownList).SelectedValue + "' order by OptTime desc");
            System.Data.DataTable ddlog = new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable;


            string result = "";
            if (ddlog != null && ddlog.Rows.Count > 0)
            {
                result = ddlog.Rows[0]["BeforeVal"].ToString();
            }
            result = Regex.Replace(result, "(\r\n){2}", "\r\n");
            this.Literal3.Text = Regex.Replace(result, "\r\n", "<br/>");
            //this.ltContent.Text = result;
            this.caonima.Visible = false;
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            IDictionary<string, object> sqlParams = new Dictionary<string, object>();
            sqlParams.Add("t-sql", "select * From V_MsgReplyOne where ID='" + this.txtID.Value.Trim() + "'");
            DataTable dt = new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable;
            var cc = dt.Rows[0]["content"].ToString();
            cc = Regex.Replace(cc, "(\r\n){2}", "\r\n");
            this.tbEditContent.Text = cc;
            this.caonima.Visible = true;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            IDictionary<string, object> sqlParams = new Dictionary<string, object>();
            sqlParams.Add("t-sql", "select * From V_MsgReplyOne where ID='" + this.txtID.Value.Trim() + "'");
            DataTable dt = new RoleBase().Instance().GetListByTSQL(sqlParams) as System.Data.DataTable;
            //new value:
            string AfterInputVal = this.tbEditContent.Text.Trim();

            if (dt != null && dt.Rows.Count > 0)
            {
                RoleBase defaultRole = new RoleBase();
                IMessagePly MsgInstance = defaultRole.Instance();
                IDictionary<string, object> sqlParamsContainer = new Dictionary<string, object>();
                sqlParamsContainer.Add("t-sql", @" insert into [DatSysNewsMonth_log] ([ID]  ,[MessageID]  ,[BeforeVal]  ,[AfterVal]  ,[ChangeType]  ,[OptTime]) 
values (newid(), '" + dt.Rows[0]["ID"].ToString() + "', '" + dt.Rows[0]["content"].ToString() + "', '" + AfterInputVal + "', 0, GetDate() ) Update [DatSysNewsMonth] set [content]='" + AfterInputVal + "' where ID='" + dt.Rows[0]["ID"].ToString() + "'");
                sqlParamsContainer.Add("acrtion", "ExecuteScalar");
                MsgInstance.GetListByTSQL(sqlParamsContainer);
                this.caonima.Visible = false;
                InitData();
            }
        }


    }
}
